<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">健康管理系统</h2>
      </template>
      <el-tabs v-model="activeTab" stretch @tab-change="handleTabChange">
        <el-tab-pane label="登录" name="login"></el-tab-pane>
        <el-tab-pane label="注册" name="register"></el-tab-pane>
      </el-tabs>

      <el-form :model="loginForm" :rules="rules" v-show="activeTab === 'login'"  ref="loginFormRef">
        <el-form-item prop="userPhone">
          <el-input v-model="loginForm.userPhone" placeholder="手机号">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" class="login-button">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 新增注册表单 -->
      <el-form
          v-show="activeTab === 'register'"
          :model="registerForm"
          :rules="registerRules"
          ref="registerFormRef"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="registerForm.userName" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="registerForm.userPhone" placeholder="手机号">
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="密码">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="registerForm.idCard" placeholder="身份证" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
                          v-model="registerForm.birthday"
                          type="date"
                          placeholder="选择日期"
                          format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD"
                          style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="registerForm.sex" placeholder="请选择性别">
            <el-option label="男" :value="1"/>
            <el-option label="女" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="registerForm.emergencyContact" placeholder="紧急联系人姓名"/>
        </el-form-item>
        <el-form-item label="紧急联系人关系" prop="emergencyRelation">
          <el-input v-model="registerForm.emergencyRelation" placeholder="紧急联系人关系"/>
        </el-form-item>
        <el-form-item label="紧急联系人电话" prop="emergencyPhone">
          <el-input v-model="registerForm.emergencyPhone" placeholder="紧急联系人电话"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="registerForm.address" placeholder="地址"/>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              :loading="registerLoading"
              @click="handleRegister"
              class="register-button"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { login,addUser} from '@/api/user'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const registerLoading = ref(false)
const activeTab = ref('login')
const loginForm = reactive({
  userPhone: '',
  password: ''
})

const rules = {
  userPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const handleTabChange = () => {
  loginFormRef.value?.resetFields()
  registerFormRef.value?.resetFields()
}
const registerForm = reactive({
  userName: '',
  userPhone: '',
  password: '',
  confirmPassword: '',
  idCard: '',
  userType:1,
  birthday: '',
  address: '',
  sex: 1,
  emergencyContact:'',
  emergencyRelation:'',
  emergencyPhone:'',
  status:'0'
})
const validatePassword = (rule: any, value: string, callback: Function) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    registerLoading.value = true

    // 这里可以调用注册接口，例如：
     await addUser(registerForm)

    ElMessage.success('注册成功')
    activeTab.value = 'login' // 切换到登录页签
  } catch (error: any) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    registerLoading.value = false
}
}
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const res = await login(loginForm.userPhone, loginForm.password)
    // 保存token和用户信息.
    console.log(res);
    if (res && res.tokenValue) {
      localStorage.setItem('token', res.tokenValue)
      localStorage.setItem('userInfo', JSON.stringify(res.user))
      ElMessage.success('登录成功')
      router.push('/dashboard')
    } else {
      ElMessage.error('登录失败：未获取到token')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

.login-title {
  text-align: center;
  margin: 0;
  color: #409EFF;
}

.login-button {
  width: 100%;
}
</style>
